package com.cleaningcloud.cld.service.impl;

import com.cleaningcloud.cld.api.domain.CldStaff;
import com.cleaningcloud.cld.domain.*;
import com.cleaningcloud.cld.domain.dto.CldProjectPostDto;
import com.cleaningcloud.cld.domain.vo.CldProjectPostSetVo;
import com.cleaningcloud.cld.domain.vo.CldProjectPostVo;
import com.cleaningcloud.cld.domain.vo.CldProjectSetVo;
import com.cleaningcloud.cld.domain.vo.CldProjectVo;
import com.cleaningcloud.cld.mapper.*;
import com.cleaningcloud.cld.service.ICldProjectSetService;
import com.cleaningcloud.common.core.constant.SecurityConstants;
import com.cleaningcloud.common.core.utils.DateUtils;
import com.cleaningcloud.common.core.utils.UniqueIdUtils;
import com.cleaningcloud.common.core.web.domain.AjaxResult;
import com.cleaningcloud.common.security.utils.SecurityUtils;
import com.cleaningcloud.erp.api.RemoteWareService;
import com.cleaningcloud.erp.api.domain.ErpWareHouse;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 项目配置Service业务层处理
 *
 * @author cleaningcloud
 * @date 2024-10-15
 */
@Service
public class CldProjectSetServiceImpl implements ICldProjectSetService {
    @Autowired
    private CldProjectSetMapper cldProjectSetMapper;

    @Autowired
    private CldProjectGroupsMapper cldProjectGroupsMapper;

    @Autowired
    private CldProjectPostMapper cldProjectPostMapper;

    @Autowired
    private CldProjectPostWagesMapper cldProjectPostWagesMapper;

    @Autowired
    private CldProjectOtherCostMapper cldProjectOtherCostMapper;

    @Autowired
    private RemoteWareService remoteWareService;

    @Autowired
    private CldProjectMapper cldProjectMapper;

    @Autowired
    private CldContractMapper cldContractMapper;

    @Autowired
    private CldStaffMapper cldStaffMapper;


    /**
     * 查询项目配置
     *
     * @param projectId 项目配置主键
     * @return 项目配置
     */
    @Override
    public CldProjectSetVo selectCldProjectSetByProjectId(Long projectId) {
        CldProjectSet cldProjectSet = cldProjectSetMapper.selectCldProjectSetByProjectId(projectId);
        // 项目配置信息为空
        if (cldProjectSet == null) {
            return null;
        }
        CldProjectSetVo cldProjectSetVo = new CldProjectSetVo();
        //获取项目信息
        CldProjectVo cldProject = cldProjectMapper.selectCldProjectByProjectId(projectId);
        BeanUtils.copyProperties(cldProjectSet, cldProjectSetVo);
        CldProjectPostWages cldProjectPostWages = new CldProjectPostWages();
        cldProjectPostWages.setProjectId(projectId);
        cldProjectSetVo.setPostWageList(cldProjectPostWagesMapper.selectCldProjectPostWagesList(cldProjectPostWages));
        CldProjectGroups cldProjectGroups = new CldProjectGroups();
        cldProjectGroups.setProjectId(projectId);
        cldProjectGroups.setNotGroupName(0L);
        cldProjectSetVo.setProjectGroupsList(cldProjectGroupsMapper.selectCldProjectGroupsList(cldProjectGroups));
        CldProjectOtherCost cldProjectOtherCost = new CldProjectOtherCost();
        cldProjectOtherCost.setProjectId(projectId);
        cldProjectSetVo.setOtherCostList(cldProjectOtherCostMapper.selectCldProjectOtherCostList(cldProjectOtherCost));
        if (cldProject != null) {
            cldProjectSetVo.setProjectName(cldProject.getProjectName());
            cldProjectSetVo.setStaffName(cldProject.getStaffName());
        }
        CldProjectPostDto cldProjectPost = new CldProjectPostDto();
        cldProjectPost.setFlag(0L);
        cldProjectPost.setProjectId(projectId);
        cldProjectSetVo.setCldProjectPostList(cldProjectPostMapper.selectCldProjectPostList(cldProjectPost));
        if (cldProjectSetVo.getCldProjectPostList() != null && !cldProjectSetVo.getCldProjectPostList().isEmpty()) {
            List<Long> staffIds = new ArrayList<>();
            for (CldProjectPost projectPost : cldProjectSetVo.getCldProjectPostList()) {
                if (projectPost.getStaffId() != null && projectPost.getStaffId() > 0) {
                    staffIds.add(projectPost.getStaffId());
                }
            }
            List<CldStaff> cldStaffList = new ArrayList<>();
            if (!staffIds.isEmpty()) {
                cldStaffList = cldStaffMapper.selectCldStaffListByStaffIds(staffIds);
            }
            cldProjectSetVo.setManageList(new ArrayList<>());
            cldProjectSetVo.setGroupList(new ArrayList<>());
            CldProjectPostVo projectPostVo = null;
            for (CldProjectGroups groups : cldProjectSetVo.getProjectGroupsList()) {
                if (!groups.getGroupName().equals("0")) {
                    projectPostVo = new CldProjectPostVo();
                    projectPostVo.setGroupName(groups.getGroupName());
                    projectPostVo.setList(new ArrayList<>());
                    for (CldProjectPost projectPost : cldProjectSetVo.getCldProjectPostList()) {
                        if (groups.getProjectGroupsId().equals(projectPost.getProjectGroupsId())) {
                            for (CldStaff cldStaff : cldStaffList) {
                                if (cldStaff.getStaffId().equals(projectPost.getStaffId())) {
                                    projectPost.setStaffName(cldStaff.getStaffName());
                                }
                            }
                            projectPostVo.getList().add(projectPost);
                        }
                    }
                    cldProjectSetVo.getGroupList().add(projectPostVo);
                }
            }
            for (CldProjectPostSetVo projectPost : cldProjectSetVo.getCldProjectPostList()) {
                if (projectPost.getGroupName() != null && projectPost.getGroupName() == 0) {
                    for (CldStaff cldStaff : cldStaffList) {
                        if (cldStaff.getStaffId().equals(projectPost.getStaffId())) {
                            projectPost.setStaffName(cldStaff.getStaffName());
                        }
                    }
                    cldProjectSetVo.getManageList().add(projectPost);
                }
            }
        }
        return cldProjectSetVo;
    }

    @Override
    public CldProjectSet getCldProjectSetByProjectId(Long projectId) {
        return cldProjectSetMapper.selectCldProjectSetByProjectId(projectId);
    }


    /**
     * 新增项目配置
     *
     * @param cldProjectSetVo 项目配置
     * @return 结果
     */
    @Override
    @Transactional
    @GlobalTransactional(rollbackFor = Exception.class)
    public int insertCldProjectSet(CldProjectSetVo cldProjectSetVo) {
        // 获取项目信息
        CldProject cldProject = cldProjectMapper.selectCldProjectByProjectId(cldProjectSetVo.getProjectId());
        //获取项目合同
        CldContract cldContract = cldContractMapper.selectCldContractByContractId(cldProjectSetVo.getContractId());
        if (cldContract == null) {
            throw new RuntimeException("合同信息不存在！");
        }
        // 存储岗位集合
        List<CldProjectPost> postList = new ArrayList<>();
        // 修改项目配置信息
        if (cldProjectSetVo.getProjectSetId() != null && cldProjectSetVo.getProjectSetId() > 0) {
            cldProjectSetMapper.updateCldProjectSet(cldProjectSetVo);
            // 岗位工资配置
            if(!cldProjectSetVo.getPostWageList().isEmpty()){
                cldProjectPostWagesMapper.deleteCldProjectPostWagesByProjectId(cldProjectSetVo.getProjectId());
                cldProjectPostWagesMapper.batchInsert(cldProjectSetVo.getPostWageList());
            }
            // 其他费用配置
            if(!cldProjectSetVo.getOtherCostList().isEmpty()){
                cldProjectOtherCostMapper.deleteCldProjectOtherCostByProjectId(cldProjectSetVo.getProjectId());
                cldProjectOtherCostMapper.batchInsert(cldProjectSetVo.getOtherCostList());
            }
            // 是否存在新增的小组
            for (CldProjectGroups cldProjectGroups : cldProjectSetVo.getProjectGroupsList()) {
                if (cldProjectGroups.getProjectGroupsId() == null) {
                    // 新增小组数据
                    cldProjectGroups.setProjectId(cldProject.getProjectId());
                    cldProjectGroupsMapper.insertCldProjectGroups(cldProjectGroups);
                    for (int i = 0; i < cldProjectGroups.getGroupNumber(); i++) {
                        CldProjectPost cldProjectPost = new CldProjectPost();
                        cldProjectPost.setProjectId(cldProjectSetVo.getProjectId());
                        cldProjectPost.setCreateBy(SecurityUtils.getUsername());
                        cldProjectPost.setCreateTime(DateUtils.getNowDate());
                        cldProjectPost.setFlag(0L);
                        cldProjectPost.setProjectPostNo(cldContract.getProjectName() + "-" + UniqueIdUtils.generateUniqueId());
                        cldProjectPost.setIsMasterDuits(0L);
                        cldProjectPost.setProjectGroupsId(cldProjectGroups.getProjectGroupsId());
                        postList.add(cldProjectPost);
                    }
                }
            }
            // 根据项目id查询项目仓
            ErpWareHouse erpWareHouse = remoteWareService.getWareHouseByProjectId(cldProject.getProjectId(), SecurityConstants.INNER);
            // 批量新增岗位
            if (!postList.isEmpty()) {
                cldProjectPostMapper.batchInsert(postList);
                erpWareHouse.setPostIdList(new ArrayList<>());
                for (CldProjectPost projectPost : postList) {
                    erpWareHouse.getPostIdList().add(projectPost.getProjectPostId());
                }
                erpWareHouse.setStaffNum(postList.size());
            }
            AjaxResult ajaxResult = remoteWareService.addWare(erpWareHouse, SecurityConstants.INNER); //生成项目岗接口
            if (ajaxResult.isError()) {
                throw new RuntimeException("生成仓库失败！");
            }

        } else {
            // 新增管理组
            CldProjectGroups projectGroups = new CldProjectGroups();
            projectGroups.setProjectId(cldProjectSetVo.getProjectId());
            projectGroups.setGroupNumber(1);
            projectGroups.setGroupName("0");
            cldProjectGroupsMapper.insertCldProjectGroups(projectGroups);

            // 新增管理岗
            CldProjectPost cldProjectPost = new CldProjectPost();
            cldProjectPost.setProjectId(cldProjectSetVo.getProjectId());
            cldProjectPost.setCreateBy(SecurityUtils.getUsername());
            cldProjectPost.setCreateTime(DateUtils.getNowDate());
            cldProjectPost.setFlag(0L);
            cldProjectPost.setProjectPostNo(cldContract.getProjectName() + "-" + UniqueIdUtils.generateUniqueId());
            // 默认主管岗
            cldProjectPost.setProjectPostName(1L);
            cldProjectPost.setProjectGroupsId(projectGroups.getProjectGroupsId());
            // 默认主职务
            cldProjectPost.setIsMasterDuits(1L);
            postList.add(cldProjectPost);
            // 新增小组岗位
            for (CldProjectGroups groups : cldProjectSetVo.getProjectGroupsList()) {
                // 新增小组数据
                groups.setProjectId(cldProject.getProjectId());
                cldProjectGroupsMapper.insertCldProjectGroups(groups);
                for (int i = 0; i < groups.getGroupNumber(); i++) {
                    cldProjectPost = new CldProjectPost();
                    cldProjectPost.setProjectId(cldProjectSetVo.getProjectId());
                    cldProjectPost.setCreateBy(SecurityUtils.getUsername());
                    cldProjectPost.setCreateTime(DateUtils.getNowDate());
                    cldProjectPost.setFlag(0L);
                    cldProjectPost.setProjectPostNo(cldContract.getProjectName() + "-" + UniqueIdUtils.generateUniqueId());
                    cldProjectPost.setIsMasterDuits(0L);
                    cldProjectPost.setProjectGroupsId(groups.getProjectGroupsId());
                    postList.add(cldProjectPost);
                }

            }
            // 岗位工资配置
            if (!cldProjectSetVo.getPostWageList().isEmpty()) {
                cldProjectPostWagesMapper.deleteCldProjectPostWagesByProjectId(cldProjectSetVo.getProjectId());
                cldProjectPostWagesMapper.batchInsert(cldProjectSetVo.getPostWageList());
            }
            // 其他费用配置
            if (!cldProjectSetVo.getOtherCostList().isEmpty()) {
                cldProjectOtherCostMapper.deleteCldProjectOtherCostByProjectId(cldProjectSetVo.getProjectId());
                cldProjectOtherCostMapper.batchInsert(cldProjectSetVo.getOtherCostList());
            }
            // 批量新增岗位
            if (!postList.isEmpty()) {
                cldProjectPostMapper.batchInsert(postList);
                for (CldProjectPost projectPost : postList) {
                    projectPost.setProjectPostNo(cldProject.getProjectName() + "-" + DateUtils.dateTime() + "-" + projectPost.getProjectPostId());
                }
                cldProjectPostMapper.batchUpdate(postList);
            }
            // 生成项目及岗位仓库
            ErpWareHouse wareHouse = new ErpWareHouse();
            wareHouse.setProjectId(cldContract.getProjectId());
            wareHouse.setFlag("Y");
            wareHouse.setCreateId(SecurityUtils.getLoginUser().getSysUser().getUserId());
            wareHouse.setCreateName(SecurityUtils.getUsername());
            wareHouse.setWareType(1L);
            wareHouse.setCreateTime(DateUtils.getNowDate());
            wareHouse.setUserPhone(cldProject.getHeadPhone());
            wareHouse.setUserId(cldProject.getUserId());
            wareHouse.setWareName(cldProject.getProjectName() + "仓");
            wareHouse.setWareAddress(cldProject.getProvince() + cldProject.getCity() + cldProject.getCounty() + cldProject.getAddress());
            CldProjectPostDto postQuery = new CldProjectPostDto();
            postQuery.setProjectId(cldProject.getProjectId());
            postQuery.setFlag(0L);
            //查询项目岗位Id集合
            List<CldProjectPostSetVo> cldProjectPosts = cldProjectPostMapper.selectCldProjectPostList(postQuery);
            if (cldProjectPosts != null && !cldProjectPosts.isEmpty()) {
                wareHouse.setPostIdList(new ArrayList<>());
                cldProjectPosts.forEach(post -> {
                    if (post.getProjectPostName() == null) {
                        wareHouse.getPostIdList().add(post.getProjectPostId());
                    } else {
                        wareHouse.setStaffId(post.getProjectPostId());
                    }
                });
                wareHouse.setStaffNum(cldProjectPosts.size() - 1);
            }
            AjaxResult ajaxResult = remoteWareService.addWare(wareHouse, SecurityConstants.INNER); //生成项目岗接口
            if (ajaxResult.isError()) {
                throw new RuntimeException("生成仓库失败！");
            }
            // 新增项目配置
            cldProjectSetMapper.insertCldProjectSet(cldProjectSetVo);
        }


        return 1;
    }


}
